<script setup>
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { userLoginService, getUserInfoService } from "@/api/user";
import { useUserStore } from "@/store";
import { showToast } from "@/utils/vant-ui";
const username = ref("");
const password = ref("");
const isPasswordVisible = ref(false);
const router = useRouter();
const checked = ref(false);
const show = ref(false);
const loading = ref(false);
// 判断用户名和密码是否都不为空，用于登录键的显示和隐藏
const isFormValid = computed(() => {
  return username.value.trim() !== "" && password.value.trim() !== "";
});
const onClickLeft = () => {
  router.go(-1);
};
const onSubmit = async (values) => {
  console.log("submit", values);
  if (!checked.value) {
    show.value = true;
  } else {
    loginSuccess();
  }
};

const togglePasswordVisibility = () => {
  isPasswordVisible.value = !isPasswordVisible.value;
};
const onClickRegister = () => {
  router.push("/register");
};
const onClickForget = (e) => {
  e.preventDefault();
};
const agreeProtocol = () => {
  show.value = false;
  checked.value = true;
  loginSuccess();
};
// 登录请求
const userLogin = () => {
  return userLoginService({
    username: username.value,
    password: password.value,
  }).then((res) => res.data);
};
// 获取用户信息
const getUserInfo = () => {
  return getUserInfoService().then((res) => res.data);
};
const loginSuccess = async () => {
  loading.value = true;
  const res = await userLogin();
  console.log(res);
  // 清除表单
  username.value = "";
  password.value = "";
  loading.value = false;
  // 登录成功后，将token保存到store中
  useUserStore().setToken(res);
  const userInfo = await getUserInfo();
  useUserStore().setUser(userInfo);
  showToast("登录成功");
  router.push("/");
  // setTimeout(() => {
  //   // 获取数据，登录成功后的操作
  //   loading.value = false;
  //   // 清除表单
  //   username.value = "";
  //   password.value = "";
  //   router.push("/");
  //   showToast("登录成功");
  // }, 1000);
};
</script>
<template>
  <div class="login">
    <!-- 头部 -->
    <div class="header">
      <van-nav-bar
        title="登录"
        left-arrow
        text-light
        right-text="帮助"
        @click-right="onClickRight"
        @click-left="onClickLeft"
      />
    </div>
    <div class="container">
      <div class="title">
        <h3>用户登录</h3>
      </div>
      <van-form @submit="onSubmit" class="form">
        <van-cell-group inset>
          <van-field
            v-model="username"
            name="用户名"
            placeholder="用户名"
            clearable
            :rules="[
              {
                required: true,
                message: '请填写用户名',
                trigger: ['onSubmit'],
              },
            ]"
          />
          <van-field
            v-model="password"
            :type="isPasswordVisible ? 'text' : 'password'"
            name="密码"
            placeholder="密码"
            :rules="[
              { required: true, message: '请填写密码', trigger: ['onSubmit'] },
            ]"
          >
            <template #right-icon>
              <van-icon
                :name="isPasswordVisible ? 'eye-o' : 'closed-eye'"
                @click="togglePasswordVisibility"
              />
            </template>
          </van-field>
        </van-cell-group>
        <!-- 左右两边添加切换到注册，和忘记密码 -->
        <div class="footer">
          <label class="register" @click.prevent="onClickRegister()">
            <a href="">注册</a>
          </label>
          <label class="forget" @click.prevent="onClickForget()">
            <a href="">忘记密码</a>
          </label>
        </div>
        <van-button
          round
          block
          :loading="loading"
          loading-type="spinner"
          native-type="submit"
          class="submit-btn"
          :disabled="!isFormValid"
        >
          登录
        </van-button>
        <div class="checkbox">
          <van-checkbox v-model="checked" icon-size="18px"> </van-checkbox>
          <div class="word">
            <span> 已阅读并同意 </span>
            <a @click.prevent="onClickProtocol('user')">《用户协议》</a>
            <span>&nbsp;和&nbsp;</span>
            <a @click.prevent="onClickProtocol('privacy')">《隐私政策》</a>
          </div>
        </div>
      </van-form>
    </div>
    <van-popup v-model:show="show" round>
      <div class="protocol">
        <h1>用户协议和隐私政策</h1>
        <div class="word">
          <span> 已阅读并同意 </span>
          <a href="">《用户协议》</a>
          <span>&nbsp;和&nbsp;</span>
          <a href="">《隐私政策》</a>
        </div>
        <van-button round block @click="agreeProtocol" class="agree">
          同意并登录
        </van-button>
        <van-button round block @click="show = false"> 不同意 </van-button>
      </div>
    </van-popup>
  </div>
</template>
<style lang="less" scoped>
// .header {
//   .van-nav-bar {
//   }
// }
.container {
  padding: 30px;
  .title {
    margin-left: 16px;
    margin-top: 40px;
    margin-bottom: 20px;
    h3 {
      color: rgb(31, 30, 37);
      font-size: 24px;
      font-weight: 5000;
    }
  }
  .form {
    .van-cell-group--inset {
      margin: 0;
    }
    .van-field {
      margin: 0;
      margin-bottom: 20px;
      padding: 0;
      padding-left: 10px;
      padding-right: 10px;
      width: 100%;
      height: 50px;
      line-height: 50px;
      border-radius: 8px;
      background-color: rgb(249, 249, 249);
    }
    .submit-btn {
      margin-top: 20px;
      width: 100%;
      border: 0;
      border-radius: 8px;
      background-color: red;
    }
    .footer {
      display: flex;
      justify-content: space-between;
      padding: 0 16px;
    }
    .checkbox {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}
.protocol {
  display: flex;
  // 切换主轴对齐方式
  flex-direction: column;
  justify-content: center;
  align-items: center;
  h1 {
    margin: 10px 80px 10px 80px;
    font-size: 14px;
    font-weight: 5000;
  }
  .van-button--round {
    border: 0;
  }
  .van-button--block {
    width: 80%;
  }
  .agree {
    margin-top: 16px;
    color: rgb(228, 193, 199);
    background-color: rgb(254, 43, 84);
  }
}
.word {
  margin-left: 5px;
  span,
  a {
    font-size: 10px !important;
  }
}
</style>
